package com.algorithm.cn.stack;

import java.util.Scanner;

/**
 * 
 * @author wangzonghui
 * @date 2020-12-24 20:25:03
 * @Description: 栈实现类
 */
public class ArrayStackDemo {
	public static void main(String[] args) {
		ArrayStack arrayStack = new ArrayStack(4);
		char key;
		boolean loop=true;  //控制是否退出菜单
		Scanner scanner = new Scanner(System.in);
		while(loop) {
			System.out.println("s(show):显示栈");
			System.out.println("e(exit):退出栈");
			System.out.println("p(push):入栈");
			System.out.println("g(g-pop):出栈");
			System.out.println("请输入你的选择");
			
			key=scanner.next().charAt(0);
			switch(key) {
				case 's':
					arrayStack.list();
					break;
				case 'p':
					System.out.println("请输入一个数");
					int  value=scanner.nextInt();
					arrayStack.push(value);
					break;
				case 'g':
					try {
						int res=arrayStack.pop();
						System.out.println("取出数据为:"+res);
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}
				break;
				
				case 'e':
					scanner.close();
					loop=false;
					break;
				default:
					break;
					
			}
		}
		System.out.println("程序退出");
	}
}

//定义一个ArrayStack 表示栈
class ArrayStack{
	private int maxSize;  //栈大小
	private int[] stack; //数组，模拟战
	private int top=-1; //top表示栈顶，初始化为-1
	
	public ArrayStack(int maxSize) {
		this.maxSize=maxSize;
		stack=new int[this.maxSize];
	}
	
	/**
	 * 栈满
	 * @return
	 */
	public boolean isFull() {
		return top==maxSize-1;
	}
	
	/**
	 * 栈空
	 */
	public boolean isEmpty() {
		return top==-1;
	}
	
	/**
	 * 入栈
	 * @param value
	 */
	public void push(int value) {
		if(isFull()) {
			System.out.println("栈满");
			return;
		}
		
		top++;
		stack[top]=value;
	}
	
	/**
	 * 出栈
	 * @return
	 */
	public int pop() {
		if(isEmpty()) {
			System.out.println("栈空");
			throw new RuntimeException("栈空，没有数据");
		}
		
		int value=stack[top];
		top--;
		return value;
	}
	
	/**
	 * 遍历栈
	 * 从栈顶开始
	 */
	public void list() {
		if(isEmpty()) {
			System.out.println("栈空，没有数据，无法遍历");
		}
		
		for(int i=top;i>=0;i--) {
			System.out.printf("stack[%d]=%d",i,stack[i]);
		}
	}
	
}

